<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <!-- 搜索 -->
      <div slot="header">
        <div style="display: flex; justify-content: space-between">
          <div class="lt">
            <el-form :inline="true">
              <el-form-item>
                <el-input
                  size="small"
                  v-model="tableData.username"
                  placeholder="管理员账号"
                />
              </el-form-item>
              <el-form-item>
                <el-input
                  size="small"
                  v-model="tableData.email"
                  placeholder="管理员邮箱"
                />
              </el-form-item>
              <el-form-item>
                <el-select
                  size="small"
                  v-model="tableData.status"
                  @clear="getSysUserList()"
                  clearable
                >
                  <el-option
                    v-for="item in statusArr"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button
                  type="primary"
                  @click="searchHandler"
                  size="small"
                  plain
                  v-permission="'permission:user:index'"
                  >搜索</el-button
                >
                <el-button @click="resetHandler" size="small">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <div class="rt">
            <el-button
              type="primary"
              size="medium"
              plain
              @click="dialogVisible = true"
              v-permission="'permission:user:update'"
              >创建用户</el-button
            >
          </div>
        </div>
      </div>
      <!-- 表格 -->
      <el-table :data="list" border style="width: 100%">
        <el-table-column prop="id" label="管理员ID" min-width="50" />

        <el-table-column prop="username" label="管理员姓名" min-width="50" />

        <el-table-column prop="phone" label="手机号" min-width="50" />

        <el-table-column prop="email" label="管理员邮箱" min-width="50" />

        <el-table-column
          prop="avatar"
          label="管理员头像"
          min-width="50"
          align="center"
        >
          <template #default="{ row }">
            <el-avatar
              size="large"
              :src="imgUrl + row.avatar"
              v-if="row.avatar"
            >
            </el-avatar>
            <el-avatar
              icon="el-icon-user-solid"
              size="large"
              shape="circle"
              src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
              fit="fill"
              v-else
            ></el-avatar>
          </template>
        </el-table-column>

        <el-table-column
          prop="roles_names"
          label="管理员角色"
          min-width="40"
          align="center"
        >
          <template #default="{ row }">
            <el-tag
              v-for="(item, index) in row.roles_names"
              :key="index"
              type="success"
              size="small"
              style="margin: 5px"
            >
              {{ item }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="添加时间" min-width="100" />

        <el-table-column
          prop="status"
          label="状态"
          align="center"
          min-width="50"
        >
          <template #default="{ row }">
            <el-switch
              :value="row.status"
              :active-value="1"
              :inactive-value="0"
              v-permission="'permission:user:changeStatus'"
            />
          </template>
        </el-table-column>

        <el-table-column label="操作" min-width="50" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              size="mini"
              @click="editHandler(row.id)"
              v-permission="'permission:user:update'"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              size="mini"
              @click="deleteHandler(row.id)"
              v-permission="'permission:user:delete'"
            />
          </template>
        </el-table-column>
      </el-table>
      <br />
      <!-- 分页 -->
      <el-pagination
        :current-page="tableData.page"
        :page-sizes="[5, 8, 10]"
        :page-size="tableData.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="count"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 弹窗 -->
    <el-dialog
      :title="!dialogData.id ? '添加管理员' : '修改管理员'"
      :visible="dialogVisible"
      width="46%"
      @close="cancelHandler"
      class="dialog"
    >
      <el-form
        ref="dataform"
        :rules="rules"
        :model="dialogData"
        label-width="100px"
        :inline="true"
      >
        <!-- 
          1
         -->
        <el-row>
          <el-col :span="12" :offset="0">
            <el-form-item label="管理员名称" prop="username">
              <el-input
                v-model="dialogData.username"
                placeholder="请输入用户名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="管理员邮箱" prop="email">
              <el-input
                v-model="dialogData.email"
                placeholder="请输入邮箱"
              /> </el-form-item
          ></el-col>

          <!-- 
          2
         -->
          <el-col :span="12" :offset="0">
            <!-- 新增密码 -->
            <el-form-item
              label="管理员密码"
              prop="password"
              v-if="!dialogData.id"
            >
              <el-input
                v-model="dialogData.password"
                placeholder="请输入密码"
              />
            </el-form-item>

            <!-- 修改密码 -->
            <el-form-item label="管理员密码" v-else>
              <el-input
                v-model="dialogData.password"
                placeholder="留空表示不修改"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="管理员手机" prop="phone">
              <el-input
                v-model="dialogData.phone"
                placeholder="请输入手机"
              /> </el-form-item
          ></el-col>
          <!-- 
          3
         -->
          <el-col :span="12" :offset="0">
            <el-form-item label="账号状态">
              <el-switch
                v-model="dialogData.status"
                :active-value="1"
                :inactive-value="0"
                active-text="启用"
                inactive-text="冻结"
              /> </el-form-item
          ></el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="管理员头像">
              <div class="flex-mid">
                <img
                  v-if="dialogData.avatar"
                  :src="imgUrl + dialogData.avatar"
                  alt=""
                  class="uploadImg"
                />
                <el-button
                  type="success"
                  size="mini"
                  @click="$refs.img.isshow = true"
                  class="el-icon-upload"
                  >选择</el-button
                >
              </div>
            </el-form-item>
          </el-col>

          <!-- 
          4
         -->
          <el-form-item label="管理员角色" size="normal" prop="roleid_list">
            <el-checkbox-group v-model="dialogData.roleid_list">
              <el-checkbox v-for="item in roleArr" :label="item.id">
                {{ item.role_name }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-row>
        <!-- 

         -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelHandler">取 消</el-button>
        <el-button type="primary" :loading="isLoading" @click="confirmHandler"
          >确 定
        </el-button>
      </span>
    </el-dialog>
    <Cropperimg ref="img" @upload="upload"></Cropperimg>
  </div>
</template>

<script>
import Cropperimg from '@/components/Cropperimg'
import {
  getSysUserList,
  delUser,
  addUser,
  getUserInfo,
  editUser,
  getRoleAll,
} from '@/api/permissionUser'

export default {
  name: 'userIndex',
  data() {
    return {
      date: null,
      tableData: {
        username: '',
        status: '',
        email: '',
        page: 1,
        limit: 10,
      },
      dialogData: {
        username: '',
        password: '',
        email: '',
        phone: '',
        avatar: '',
        roleid_list: [],
        status: 1,
      },
      list: [],
      dialogVisible: false,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'change' },
        ],
        name: [{ required: true, message: '请输入用户名', trigger: 'change' }],
        phone: [
          { required: true, message: '请输入用户名', trigger: 'change' },
          {
            pattern: /^1(3|4|5|7|8)\d{9}$/,
            message: '请输入合法手机号',
            trigger: 'change',
          },
        ],

        email: [
          { required: true, message: '请输入邮箱', trigger: 'change' },
          {
            pattern:
              /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g,
            message: '请输入正确的邮箱',
            trigger: 'change',
          },
        ],
        roleid_list: [
          { required: true, message: '请选择角色', trigger: 'change' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
          {
            pattern: /^[a-zA-Z0-9]{6,12}$/,
            message: '请输入6-12位密码,必须包含字母和数字',
            trigger: 'change',
          },
        ],
      },
      isLoading: false,
      count: 0,
      statusArr: [
        {
          value: '',
          label: '全部',
        },
        {
          value: '1',
          label: '正常',
        },
        {
          value: '0',
          label: '禁用',
        },
      ],
      roleArr: [],
      imgUrl: '',
    }
  },
  components: {
    Cropperimg,
  },
  created() {
    this.getSysUserList()
    this.getRoleAll()
  },
  methods: {
    // 分页器
    handleSizeChange(val) {
      console.log(val)
      this.tableData.limit = val
      this.getSysUserList()
    },
    handleCurrentChange(val) {
      this.tableData.page = val
      if (this.tableData.page !== 1 && this.list < 1) {
        this.tableData--
      }
      this.getSysUserList()
    },

    // 获取列表
    async getSysUserList() {
      const data = await getSysUserList(this.tableData)
      this.list = data.list
      this.count = data.total
    },

    // 点击搜索
    async searchHandler() {
      await this.getSysUserList()
    },

    // 重置
    resetHandler() {
      this.tableData = {
        username: '',
        status: '',
        email: '',
        page: 1,
        limit: 10,
      }
      this.getSysUserList()
    },

    // 删除
    async deleteHandler(id) {
      console.log('点击删除，id+', id)
      try {
        await this.$confirm('确定删除？')
        await delUser(id)
      } catch (error) {
        return
      }
      await this.getSysUserList()
      this.$message.success('删除成功')
    },

    // 确定按钮
    async confirmHandler() {
      this.isLoading = true
      try {
        await this.$refs.dataform.validate()
      } catch (error) {
        this.isLoading = false
        return
      }
      try {
        if (this.dialogData.id) {
          await editUser(this.dialogData)
          this.$message.success('修改成功')
        } else {
          await addUser(this.dialogData)
          console.log('发送数据', this.dialogData)
          this.$message.success('添加成功')
        }
        this.$store.dispatch('user/getInfo')
      } catch (error) {
        this.$message.error(error.message)
        // console.log(error)
      }
      this.isLoading = false
      this.getSysUserList()
      this.cancelHandler()
    },

    // 取消事件
    cancelHandler() {
      this.dialogVisible = false
      this.dialogData = {
        username: '',
        password: '',
        email: '',
        phone: '',
        avatar: '',
        roleid_list: [],
        status: 1,
      }
      this.$refs.dataform.resetFields()
    },

    // 编辑按钮
    async editHandler(id) {
      this.isLoading = true
      this.dialogData = await getUserInfo(id)
      console.log('this.dialogData', this.dialogData)
      this.dialogVisible = true
      this.isLoading = false
    },

    // 全部角色
    async getRoleAll() {
      const { list } = await getRoleAll()
      this.roleArr = list
    },

    upload(val) {
      this.dialogData.avatar = val.url
      this.$refs.img.isshow = false
    },
  },
  mounted() {
    this.imgUrl = process.env.VUE_APP_BASE_API
  },
}
</script>
<style lang="scss" scoped>
::v-deep .el-tree__empty-block {
  .el-tree__empty-text {
    width: 50%;
  }
}
::v-deep .el-form-item {
  margin-bottom: 0px;
}
.dialog {
  .el-form-item {
    margin-bottom: 20px;
  }
}

.flex-mid {
  display: flex;
  align-items: center;

  .uploadImg {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    margin-right: 20px;
  }
}
</style>
